package string.nowcoder;

/**
 * @author yuisama
 * @date 2022/09/21 13:21
 * 牛客字符串转整数
 * https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&&tqId=11202&rp=6&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking
 **/
public class Str2Int {
    public int StrToInt(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        // 先用long，避免溢出
        long ret = 0;
        int flag = 1;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            Integer.parseInt("123");
            if (i == 0 && c == '+') {
                continue;
            }
            if (i == 0 && c == '-') {
                flag = -1;
            }else {
                if (!Character.isDigit(c)) {
                    // 碰到一个非法字符，直接0
                    return 0;
                }else {
                    ret = ret * 10 + (c - '0');
                    // 越界
                    if (ret > Integer.MAX_VALUE) {
                        return 0;
                    }
                }
            }
        }
        ret = ret * flag;
        return (int) ret;
    }
}